package record;

import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.qingning.qn.R;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import base.BaseActivity;
import base.httputils.JSONUtils;
import base.httputils.ProgressDialogHttp;


public class RecordVoiceActivity extends BaseActivity implements View.OnClickListener {

    TextView tvVoice, tvPath;
    Button btPlay, btSub, btAgain;
    VoiceSendingView voiceSending;
    LinearLayout llResult;

    // 录音工具
    private RecorderUtil recorder = new RecorderUtil();

    // 播放语音工具
    private MediaPlayer player;


    /**
     * 按下的y坐标
     */
    private float startY;
    /**
     * 是否已经取消发送
     */
    boolean isCancle = false;

    /**
     * 是否有已经恢复发送
     */
    boolean isResume = false;

    File voice = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_record_voice);
        initView();
        addListener();
    }


    public void initView() {
        tvVoice = (TextView) findViewById(R.id.tvVoice);
        tvPath = (TextView) findViewById(R.id.tvPath);
        btPlay = (Button) findViewById(R.id.btPlay);
        btSub = (Button) findViewById(R.id.btSub);
        btAgain = (Button) findViewById(R.id.btAgain);
        llResult = (LinearLayout) findViewById(R.id.llResult);
        voiceSending = (VoiceSendingView) findViewById(R.id.voiceSending);
        player = new MediaPlayer();
        player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                btPlay.setClickable(true);
            }
        });
    }


    public void addListener() {
        btPlay.setOnClickListener(this);
        btSub.setOnClickListener(this);
        btAgain.setOnClickListener(this);
        tvVoice.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        startY = event.getRawY();
                        // 按下开始说话
                        tvVoice.setText("松开 结束");
                        tvVoice.setBackgroundResource(R.drawable.btn_voice_down);
                        startSendVoice();
                        break;
                    case MotionEvent.ACTION_UP:
                        // 抬起停止说话
                        tvVoice.setText("按住 说话");
                        tvVoice.setBackgroundResource(R.drawable.btn_voice_up);
                        endSendVoice();
                        if (startY - event.getRawY() < 200) {
                            voice = new File(recorder.getFilePath());
                            // 上传语音文件
                            Toast.makeText(RecordVoiceActivity.this, "录制成功", Toast.LENGTH_SHORT).show();
                            llResult.setVisibility(View.VISIBLE);
                            tvPath.setText("音频地址：" + recorder.getFilePath());
                        }
                        startY = 0;
                        break;
                    case MotionEvent.ACTION_MOVE:
                        if (startY - event.getRawY() > 200) {
                            // 滑动到范围内
                            cancleRecord();
                        } else {
                            // 滑出范围内
                            resumeRecord();
                        }
                        break;
                }
                return true;
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btPlay:
                try {
                    player.reset();
                    player.setDataSource(new FileInputStream(voice).getFD());
                    player.prepare();
                    player.start();
                    btPlay.setClickable(false);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.btAgain:
                if (player.isPlaying())
                    player.stop();
                if (voice != null)
                    voice.delete();
                tvPath.setText("");
                llResult.setVisibility(View.GONE);
                break;
            case R.id.btSub:
                upLoadFileData(recorder.getFilePath());
//                Intent intent = new Intent();
//                intent.putExtra("url", recorder.getFilePath());
//                setResult(RESULT_OK, intent);
//                finish();
                break;
        }
    }
    public void upLoadFileData(String filePath){
        ProgressDialogHttp.showProgressDialog(this);
        OkGo.<String>post(base.httputils.Constant.fileuoload)//
                .tag(RecordVoiceActivity.this)//
                .params("file",new File(filePath))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        ProgressDialogHttp.disMissDialog();
                        //注意这里已经是在主线程了
                        if (response!=null){
                            String data = response.body();//这个就是返回来的结果
                            FileUpLoad fileUpLoad=    JSONUtils.parserObject(data, FileUpLoad.class);
//                            try {
//                                H5Service h5Service = MPFramework.getExternalService(H5Service.class.getName());
//                                final H5Page h5Page = h5Service.getTopH5Page();
//                                Log.e("sss::",h5Page.toString());
//                                if (null != h5Page) {
//                                    JSONObject jo = new JSONObject();
//                                    jo.put("fileName",fileUpLoad.getData().get(0).getFileName());
//                                    jo.put("fileUrl",fileUpLoad.getData().get(0).getFileUrl());
//                                    jo.put("realFileName",fileUpLoad.getData().get(0).getRealFileName());
//                                    jo.put("fileType",fileUpLoad.getData().get(0).getFileType());
//                                    // native 向小程序发送事件的方法
//                                    // 第一个是事件名称，第二个是参数，第三个默认传 null
//                                    h5Page.getBridge().sendDataWarpToWeb("audioData",jo, null);
//                                    RecordVoiceActivity.this.finish();
//                                }
//                            }catch (Exception e){
//
//                            }
                        }else{
                            Toast.makeText(RecordVoiceActivity.this, "文件选取失败", Toast.LENGTH_SHORT).show();
                            RecordVoiceActivity.this.finish();
                        }
                    }
                    @Override
                    public void onError(Response<String> response) {
                        Toast.makeText(RecordVoiceActivity.this, "文件选取失败", Toast.LENGTH_SHORT).show();
                        RecordVoiceActivity.this.finish();
                        super.onError(response);
                    }
                });
    }

    /**
     * 开始发送语音消息
     */
    public void startSendVoice() {
        voiceSending.setVisibility(View.VISIBLE);
        voiceSending.showRecording();
        recorder.startRecording();
    }

    /**
     * 结束发送语音消息
     */
    public void endSendVoice() {
        voiceSending.release();
        voiceSending.setVisibility(View.GONE);
        recorder.stopRecording();
    }


    private void cancleRecord() {
        if (!isCancle) {
            isCancle = true;
            isResume = false;
            voiceSending.showCancel();
        }
    }

    private void resumeRecord() {
        if (!isResume) {
            isResume = true;
            isCancle = false;
            voiceSending.showRecording();
        }
    }

    public void stop() {
        if (player != null && player.isPlaying()) {
            player.stop();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stop();
    }
}
